// src/components/TopicEditor.tsx
import React, {
  useState,
  useRef,
  useEffect,
  forwardRef,
  useImperativeHandle,
} from 'react';
import { View, Textarea, RichText } from '@tarojs/components';
import './index.less';

export interface TopicEditorRef {
  /** 在光标位置插入话题，不含 # */
  insertTopic(topic: string): void;
  /** 获取包括 #话题# 在内的文本 */
  getValue(): string;
}

export interface TopicEditorProps {
  /** 占位文本 */
  placeholder?: string;
  /** 文本变化回调 */
  onChange?(value: string): void;
}

const TopicEditor = forwardRef<TopicEditorRef, TopicEditorProps>(
  ({ placeholder, onChange }, ref) => {
    const [value, setValue] = useState(''); // 文本内容
    const [cursor, setCursor] = useState(0); // 光标位置
    const prevRef = useRef(''); // 上次文本

    // 暴露方法
    useImperativeHandle(ref, () => ({
      insertTopic(topic: string) {
        const pos = cursor;
        const head = value.slice(0, pos);
        const tail = value.slice(pos);
        const tag = `#${topic}#`;
        const newVal = head + tag + tail;
        setValue(newVal);
        setCursor(head.length + tag.length);
      },
      getValue() {
        return value;
      },
    }));

    // 通知父组件
    useEffect(() => {
      // onChange?.(value);
    }, [value]);

    // 处理输入与删除完整话题
    const handleInput = (e: any) => {
      const curVal = e.detail.value;
      const curPos = e.detail.cursor;

      // 删除检测
      if (curVal.length < prevRef.current.length) {
        if (curVal[curPos - 1] === '#') {
          const start = curVal.lastIndexOf('#', curPos - 2);
          if (start >= 0) {
            const maybe = curVal.slice(start, curPos);
            if (/^#[^#]+#$/.test(maybe)) {
              const newVal = curVal.slice(0, start) + curVal.slice(curPos);
              setValue(newVal);
              prevRef.current = newVal;
              setCursor(start);
              return;
            }
          }
        }
      }
      // 普通输入
      setValue(curVal);
      prevRef.current = curVal;
      setCursor(curPos);
    };

    // 转 HTML 高亮话题
    const toHtml = (text: string) =>
      text
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/#([^#]+)#/g, '<span class="topic">#$1#</span>');

    return (
      <View className="topic-editor">
        <RichText className="display" nodes={toHtml(value)} />
        <Textarea
          className="input"
          value={value}
          maxlength={500}
          placeholder={placeholder}
          cursor={cursor}
          autoHeight
          disableDefaultPadding
          adjustPosition={false}
          onFocus={(e: any) => setCursor(e.detail.cursor)}
          onInput={handleInput}
        />
      </View>
    );
  }
);

export default TopicEditor;
